//
//  JKLogView.m
//  RunloopTableViewDemo
//
//  Created by Jack on 2021/6/30.
//

#import "JKLogView.h"
#import "JKLogManager.h"
static NSString *const cId = @"logCell";

@interface JKLogView ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation JKLogView{
    UITableView *_logTableView;
    NSArray *_dataArray;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _logTableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _logTableView.delegate = self;
        _logTableView.dataSource = self;
        [self addSubview:_logTableView];
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    _logTableView.frame = self.bounds;
}

#pragma mark - Public
- (void)addLogToView:(NSString *)log{
    if (!log || ![log isKindOfClass:[NSString class]] || log.length == 0) {
        return;
    }
    _dataArray = [[[JKLogManager sharedManager] allLogs] copy];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(_dataArray.count - 1) inSection:0];
    NSArray *index = @[indexPath];
    [_logTableView insertRowsAtIndexPaths:index withRowAnimation:(UITableViewRowAnimationAutomatic)];
    [_logTableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:cId];
    }
    NSString *log = [NSString stringWithFormat:@"%@-%@",@(indexPath.row),_dataArray[indexPath.row]];
    cell.textLabel.text = log;
    return cell;
}

@end
